package com.it.chatgptchen;

import com.it.chatgptchen.chatgpt.OpenAiClient;
import com.it.chatgptchen.chatgpt.interceptor.OpenAILogger;
import com.it.chatgptchen.chatgpt.interceptor.OpenAiResponseInterceptor;
import com.it.chatgptchen.controller.FirstKeyStrategy;
import okhttp3.OkHttpClient;
import okhttp3.logging.HttpLoggingInterceptor;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;

import java.net.InetSocketAddress;
import java.net.Proxy;
import java.util.List;
import java.util.concurrent.TimeUnit;

@SpringBootApplication
public class ChatgptChenApplication {
    @Value("${chatgpt.apiKey}")
    private List<String> apiKey;

    @Value("${chatgpt.apiHost}")
    private String apiHost;

    @Value("${chatgpt.ip}")
    private String apiIp;

    @Value("${chatgpt.port}")
    private int apiPost;

    public static void main(String[] args) {
        SpringApplication.run(ChatgptChenApplication.class, args);
    }

    @Bean
    public OpenAiClient openAiClient() {
//        //本地开发需要配置代理地址
        //可以为null
        Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(apiIp,apiPost));
        HttpLoggingInterceptor httpLoggingInterceptor = new HttpLoggingInterceptor(new OpenAILogger());
        //！！！！千万别再生产或者测试环境打开BODY级别日志！！！！
        //！！！生产或者测试环境建议设置为这三种级别：NONE,BASIC,HEADERS,！！！
        httpLoggingInterceptor.setLevel(HttpLoggingInterceptor.Level.HEADERS);
        OkHttpClient okHttpClient = new OkHttpClient
                .Builder()
                .proxy(proxy)
                .addInterceptor(httpLoggingInterceptor)
                .addInterceptor(new OpenAiResponseInterceptor())
                .connectTimeout(10, TimeUnit.SECONDS)
                .writeTimeout(30, TimeUnit.SECONDS)
                .readTimeout(30, TimeUnit.SECONDS)
                .build();
        return OpenAiClient.builder()
                //支持多key传入，请求时候随机选择
                .apiKey(apiKey)
                .apiHost(apiHost)
                //自定义key的获取策略：默认KeyRandomStrategy
                //.keyStrategy(new KeyRandomStrategy())
                .keyStrategy(new FirstKeyStrategy())
                .okHttpClient(okHttpClient)
                .build();
    }
}
